package com.example.handler;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object temp = session.getAttributes().get("user");
        System.out.println(temp);
        logger.info("连接成功 " + session.getId() + " " + session.getRemoteAddress());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
        throws Exception {
        logger.info("关闭成功  ");

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message)
        throws Exception {
        logger.info(message.getPayload() + session.getId());

        session.sendMessage(new TextMessage("服务端时间为" + new Date().getTime()));

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception)
        throws Exception {
        logger.error(session.getId(), exception);
        session.close(CloseStatus.SERVER_ERROR);
    }
}
